package com.grace.cms.general.controller.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.grace.cms.search.lucene.service.LuceneSearchService;
import com.grace.common.core.controller.BaseController;
import com.grace.common.core.domain.AjaxResult;

/**
 * 搜索控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/{themeName}/api/search")
public class SearchApiController extends BaseController {

    @Autowired
    private LuceneSearchService luceneSearchService;


    @GetMapping("/query")
    public AjaxResult search(
            @PathVariable("themeName") String themeName,
            @RequestParam("query") String query,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "sortField", defaultValue = "publishDate") String sortField,
            @RequestParam(value = "sortOrder", defaultValue = "desc") String sortOrder) {
        try {
            return success(luceneSearchService.search(query, page, size, sortField, sortOrder));
        } catch (Exception e) {
            throw new RuntimeException("Search failed: " + e.getMessage(), e);
        }
    }

    @GetMapping("/query/{type}")
    public AjaxResult searchByType(
            @PathVariable("themeName") String themeName,
            @RequestParam("query") String query,
            @PathVariable("type") String type,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "sortField", defaultValue = "publishDate") String sortField,
            @RequestParam(value = "sortOrder", defaultValue = "desc") String sortOrder) {
        try {
            return success(luceneSearchService.searchByType(query, type, page, size, sortField, sortOrder));
        } catch (Exception e) {
            throw new RuntimeException("Search failed: " + e.getMessage(), e);
        }
    }

}